<template>
  <div style="text-align: start;">
    <el-button type="primary" style="margin: 20px;" @click="basic.dialogVisible = 'true'">课程申请</el-button>
    <Table ref="mytable" :param="table"></Table>

    <!-- 显示课程分类的弹出框 -->
    <el-dialog
      title="课程分类"
      :visible.sync="basic.dialogVisible2"
      width="30%">

      <!-- 树形结构 -->
      <el-tree
        ref="mytree"
        :data="data"
        :props="defaultProps"
        node-key="id"
        default-expand-all="true"
        @node-click="handleNodeClick"></el-tree>

    </el-dialog>

    <!-- 新增课程的弹出框 -->
    <el-dialog
      title="课程申请"
      :visible.sync="basic.dialogVisible"
      width="60%">
      <div style="margin: 20px;">
        <div style="margin-bottom: 10px;">
          课程标题: <el-input placeholder="课程标题" style="width: 50%;" v-model="form.subject"></el-input>
        </div>
        <div style="display: flex; flex-direction: row;">
          课程封面:
          <el-upload
            style="margin-left: 10px;"
            class="avatar-uploader"
            :action="updatePath"
            :on-success="uploadSucc"
            :show-file-list="false">
            <!-- <img  class="avatar"> -->
            <el-image
                  class="avatar"
                  v-if="imgSrc" :src="imgSrc"
                  fit="cover"></el-image>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </div>

        <div style="margin-bottom: 10px;">
          课程分类: <el-button type="success" @click="basic.dialogVisible2='true'">{{typeName}}</el-button>
        </div>

        <!-- 规格的循环 -->
        <div v-for="g in guiges" style="margin-bottom: 10px;">
          <!-- 规格名称 -->
          {{g.gname}}:
            <!-- 规格可选项 -->
            <el-select v-model="g.selected" placeholder="请选择">
              <el-option
                v-for="val in g.vals"
                :key="val.id"
                :label="val.val"
                :value="val.id">
              </el-option>
            </el-select>
        </div>

        <div style="margin-bottom: 10px;">
          课程价格: <el-input placeholder="数量课程价格" style="width: 50%;" v-model="form.price"></el-input>
        </div>
        <div style="margin-bottom: 10px;">
          开课时间: <el-date-picker
                      v-model="form.beginTime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
        </div>
        <div style="margin-bottom: 10px;">
          结课时间: <el-date-picker
                      v-model="form.endTime"
                      value-format="yyyy-MM-dd HH:mm:ss"
                      type="date"
                      placeholder="选择日期">
                    </el-date-picker>
        </div>

        <div style="margin-bottom: 10px;">
          课程简介: <MyEditor ref="myeditor" style="margin-top: 5px;"></MyEditor>
        </div>
      </div>

      <el-button type="success" @click="insertCourse">添加</el-button>

    </el-dialog>

    <!-- 课程明细的弹窗 -->
    <el-dialog
      title="课程明细"
      :visible.sync="basic.dialogVisible3"
      width="60%">

      <!-- 日历 -->
      <el-calendar v-model="calendarDate">
        <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
        <template
          slot="dateCell"
          slot-scope="{date, data}">
          <div :class="data.isSelected ? 'is-selected' : ''">
            {{ data.day.split('-').slice(1).join('-') }}


            <div style="font-size: 10px; white-space: nowrap; overflow: hidden; text-overflow:ellipsis; width: 100%; margin-top: 10px;" v-if="courseDesc[data.day.split('-').slice(1).join('-')]">
              {{courseDesc[data.day.split('-').slice(1).join('-')].title}}
            </div>
            <div style="font-size: 10px; white-space: nowrap; overflow: hidden; text-overflow:ellipsis; width: 100%;" v-if="courseDesc[data.day.split('-').slice(1).join('-')]">
              {{formatTime(courseDesc[data.day.split('-').slice(1).join('-')].descBeginTime) + ' 至 ' + formatTime(courseDesc[data.day.split('-').slice(1).join('-')].descEndTime)}}
            </div>
          </div>
        </template>
      </el-calendar>
    </el-dialog>

    <!-- 添加课程章节 -->
    <el-dialog
      title="新增课程章节"
      :visible.sync="basic.dialogVisible4"
      width="60%">
      <div style="margin: 20px;">
        <div style="margin-bottom: 10px;">
          授课日期: <el-input placeholder="授课日期" style="width: 50%;" v-model="form2.date" disabled></el-input>
        </div>
        <div style="margin-bottom: 10px;">
          章节标题: <el-input placeholder="章节标题" style="width: 50%;" v-model="form2.title"></el-input>
        </div>

        <div style="margin-bottom: 10px;">
          课程类型:
            <el-radio-group v-model="form2.type">
              <el-radio :label="0">收费</el-radio>
              <el-radio :label="1">免费试听</el-radio>
            </el-radio-group>
        </div>

        <div style="margin-bottom: 10px;">
          授课时间:   <el-time-select
                      v-model="form2.begin"
                      value-format="HH:mm:ss"
                      :picker-options="{
                          start: '06:00',
                          step: '00:30',
                          end: '23:00'
                        }"
                      placeholder="选择授课时间">
                    </el-time-select>
        </div>
        <div style="margin-bottom: 10px;">
          结课时间: <el-time-select
                      v-model="form2.end"
                      value-format="HH:mm:ss"
                      :picker-options="{
                          start: '06:00',
                          step: '00:30',
                          end: '23:00'
                        }"
                      placeholder="选择结束时间">
                    </el-time-select>
        </div>
      </div>

      <el-button type="success" @click="insertCourseDesc">添加</el-button>
    </el-dialog>

  </div>
</template>

<script>
  import Table from "./Table"
  import MyEditor from "./MyEditor"
  export default{
    components: {
      Table,
      MyEditor
    },
    data() {
      return {
        updatePath: "http://localhost/file/img/uploader",//上传地址
        imgSrc: "",//封面要回显的url
        gvalid: "",
        typeName: "选择课程分类",
        data: [],
        imageUrl: '',
        guiges: [],//指定分类下的规格列表
        calendarDate: null, //选中的时间
        courseDesc: {}, //课程明细列表
        form: {

        },
        form2: {
          type: 0,
          cid: null
        },
        basic:{
          dialogVisible: false,
          dialogVisible2: false,
          dialogVisible3: false,
          dialogVisible4: false
        },
        table: {
          //表头
          title: [
            {title:"课程编号", attr:"id"},
            {title:"课程标题", attr:"subject"},
            {title:"课程封面", attr:"fengmian", type:"img"},
            {title:"课程价格", attr:"price"},
            {title:"开始时间", attr:"beginTime"},
            {title:"结束时间", attr:"endTime"}
          ],
          //请求的url
          url: "/course/info/listByTid",
          //请求的数据
          data: {},
          //后续的操作按钮
          btns: {
            enable: true,
            //操作列表
            actions: [
              {
                btnName: "课时调整", callable: (val) => {
                  this.showCourseDesc(val.id);
                },
              },
              {
                btnName: "开始上课", callable: (val) => {
                  //查询是否有合适的课程
                  this.$.ajax({
                    url: "/course/info/querybegin",
                    data: {
                      cid: val.id
                    },
                    success: (data) => {
                      console.log("可以上课了... 跳转到屏幕共享页面...");
                      // this.$router.push("/CoursePlayer/" + val.id);
                      let routeUrl = this.$router.resolve({
                        path: "/CoursePlayer/" + val.id// 这里的路径就可以正常的写，不需要添加_blank: true
                      })
                      window.open(routeUrl.href, '_blank')
                    }
                  });
                }
              }
            ]
          },
          //分页参数
          page: {
            //是否需要开启分页的功能
            enable: true,
            //当前第几页
            pageNum: 1,
            //每页多少行记录
            pageSize: 5
          }
        }
      }
    },
    methods: {
      //图片上传成功后触发
      handleAvatarSuccess(res, file) {
        // this.imageUrl = URL.createObjectURL(file.raw);
      },
      //查询课程分类列表 - 树形结构
      queryCourseTypeTree(){
        this.$.ajax({
          url: "/course/type/treeList",
          success: (data) => {
            this.data = data;
          }
        });
      },
      //课程分类树的点击方法
      handleNodeClick(data) {
        console.log(data);
        if(data.level == 3) {
          this.form.tid = data.id;//选择的分类id
          this.typeName = data.label;//选择的分类的名称
          this.basic.dialogVisible2 = false;//关闭弹窗

          //动态的加载当前分类下的规格列表
          this.queryCourseTypeGuiges();
        } else {
          this.$message.warning("必须选择三级分类");
        }
      },
      //根据课程分类查询课程分类下的所有规格列表
      queryCourseTypeGuiges(){
        //
        this.$.ajax({
          url: "/course/type/guigeListSelected",
          data: {
            tid: this.form.tid
          },
          success: (data) => {
            console.log("课程分类规格列表：", data);
            this.guiges = data;
          }
        });
      },
      //封面上传
      uploadSucc(resp){
        console.log("上传成功！", resp);
        this.form.fengmian = resp.data;

        //回显头像
        this.imgSrc = "http://localhost/file/img/download?imgName=" + resp.data;
      },
      //新增课程
      insertCourse(){
        console.log(this.guiges); //动态规格的参数
        console.log(this.$refs.myeditor.html); //富文本的参数
        console.log(this.form); //提交的参数

        this.form.info = this.$refs.myeditor.html;
        //预处理规格信息
        var gs = [];
        for(var i = 0; i < this.guiges.length; i++){
             var guige = this.guiges[i];
             var g = {};
             g.gid = guige.id;
             g.selected = guige.selected;
             gs.push(g);
        }
        this.form.guiges = JSON.stringify(gs);


        //ajax请求
        this.$.ajax({
          type: "POST",
          url: "/course/info/insert",
          data: this.form,
          success: (data) => {
             //关闭弹窗
             this.basic.dialogVisible = false;
             //刷新表格
             this.$refs.mytable.request();
          }
        });
      },
      //展示课程详情
      showCourseDesc(cid){
        //显示弹窗
        this.basic.dialogVisible3 = true;
        this.form2.cid = cid;
        //查询当前课程下的所有 课程详情信息
        this.$.ajax({
          url: "/course/info/querydesc",
          data: {
            cid: cid
          },
          success: (data) => {
            this.courseDesc = data;
          }
        });
      },
      //新增课程章节
      insertCourseDesc(){
        this.form2.descBeginTime = this.form2.date + " " + this.form2.begin + ":00";
        this.form2.descEndTime = this.form2.date + " " + this.form2.end + ":00";
        console.log("新增课程章节", this.form2);

        this.$.ajax({
          url: "/course/info/insertdesc",
          data: this.form2,
          success: (data) => {
            this.basic.dialogVisible4 = false;
            this.$message.success("课程章节添加成功！");
            this.showCourseDesc(this.form2.cid);
            this.form2 = {type: 0, cid: this.form2.cid};
          }
        });
      },
      //格式化时间
      formatTime (date){
        var dateObj = new Date(date);
        var h = dateObj.getHours();
        var m = dateObj.getMinutes();
        return (h < 10 ? "0" + h : h) + ":" + (m < 10 ? "0" + m : m);
      },
      //格式化日期
      formateDate (date) {
        var dateObj = new Date(date);
        var y = dateObj.getFullYear();
        var m = dateObj.getMonth() + 1;
        var d = dateObj.getDate();
        return y + "-" + (m < 10 ? "0" + m : m) + "-" + (d < 10 ? "0" + d : d);
      }
    },
    mounted(){
      this.queryCourseTypeTree();
    },
    watch: {
      calendarDate(data) {
        if(data) {
          this.form2.date = this.formateDate(data);
          //弹出框 输入课程明细
          this.basic.dialogVisible4 = true;
        }
      }
    }
  }
</script>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .is-selected {
    color: #1989FA;
  }
</style>
